const { goodsDetail, addFavourite, cancelFavourite, addCart, evaluateList } = require('../../api/goods')
const { getCreditWithShare } = require('../../api/user')
const { bindUserInfo } = require('../../api/user')
const { API_OK } = require('../../utils/setting')
const app = getApp()

Page({
  data: {
    loading: false,
    headerBtnType: 'circle',
    headerBgColor: 'transparent',
    userInfo: null,
    tabIndex: 0,
    confirmType: '', // 规格弹窗的确定按钮类型（提交购物车 cart/提交订单 order）
    showSpecifications: false, // 是否展示规格选择弹窗
    goodsType: null, // 商品类型 1普通 2积分 3周边
    goodsId: null, // 商品id（spuid）
    images: [], // 商品轮播图
    video: '', // 商品相关的视频地址
    name: '', // 商品名称
    price: '', // 售价
    originPrice: '', // 原价（划线价）
    likeNum: 0, // 喜欢该商品的人数
    isFavourite: false, // 是否已经收藏
    detail: '', // 商品信息
    sku: {}, // sku 列表
    selectedSku: null, // 当前选中的sku
    specification: [], // 商品规格信息
    selectedSpecification: [], // 当前选中的规格
    evaluates: [], // 评价列表
    number: 1, // 加入购物车 / 立即购买的商品数量
  },
  pageData: {
    refresh: false,
    goodsId: null,
    page: 1,
    canLoadMore: false,
    submit: false // 提交请求的防抖属性
  },
  onLoad: function (options) {
    wx.setNavigationBarColor({ frontColor: '#ffffff', backgroundColor: '#000000' })
    this.pageData.goodsId = options.id
  },
  onReady() {
    wx.showLoading({ title: '拼命加载中', mask: true })

    if (wx.getStorageSync('token')) {
      this.setUserInfo()
      this.getGoodsDetail()
      this.getEvaluate()
    } else {
      app.getTokenFailedCallback = wx.hideLoading
      app.tokenReadyCallback = () => {
        this.setUserInfo()
        this.getGoodsDetail()
        this.getEvaluate()
      }
    }
  },
  async onShow() {
    if (!this.pageData.refresh) return
    wx.showLoading({ title: '拼命加载中', mask: true })
    await this.getGoodsDetail()
    this.pageData.refresh = false
  },
  onReachBottom() {
    if (this.data.tabIndex === 0 || !this.pageData.canLoadMore) return
    this.pageData.page += 1
    this.getEvaluate()
  },
  onShareAppMessage() {
    getCreditWithShare()
    return {
      title: this.data.name || '商品',
      path: `/pages/goods-detail/goods-detail?id=${this.pageData.goodsId}`
    }
  },
  /**
   * 从 globalData 中获取用户信息
   */
  setUserInfo() {
    this.setData({ userInfo: app.globalData.userInfo })
  },
  /**
   * 获取用户授权信息
   */
  async getUserInfo(e) {
    if (e.detail.errMsg !== 'getUserInfo:ok') return
    try {
      wx.showLoading({ title: '拼命加载中', mask: true })
      const res = await bindUserInfo({
        data: {
          nickname: e.detail.userInfo.nickName,
          avatar: e.detail.userInfo.avatarUrl
        },
        callback: wx.hideLoading
      })
      if (res.code === API_OK) {
        wx.showToast({ title: '授权成功', icon: 'success', duration: 1500 })
        this.setData({ userInfo: JSON.parse(e.detail.rawData) })
      } else {
        wx.showToast({ title: '授权失败，请稍后再试', duration: 1500, icon: 'none' })
      }
    } catch(err) {
      console.warn(err)
      wx.hideLoading()
    }
  },
  changeIndex(e) {
    this.setData({tabIndex: e.detail.index})
  },
  /**
   * 打开规格弹窗
   */
  chooseSpecification(e) {
    if (this.data.specification) {
      this.setData({ showSpecifications: true, confirmType: e.currentTarget.dataset.type })
    } else {
      this.setData({ confirmType: e.currentTarget.dataset.type })
      this.submit()
    }
  },
  /**
   * 修改规格
   */
  changeSpecification({ currentTarget }) {
    // console.log(currentTarget)
    const { id, index } = currentTarget.dataset
    this.data.selectedSpecification[index] === id
      ? this.data.selectedSpecification.splice(index, 1, null)
      : this.data.selectedSpecification.splice(index, 1, id)
    let specificationStr = this.data.selectedSpecification.join('_')
    this.setData({
      selectedSpecification: this.data.selectedSpecification,
      selectedSku: this.data.sku[specificationStr] || null
    })
    this.checkSpecificationChosable()
  },
  /**
   * 检查规格的可选状态
   */
  checkSpecificationChosable() {
    const combination = [] // 规格组合
    for (let index in this.data.specification) {
      combination[index] = this.data.selectedSpecification[index] || ''
    }
    this.data.specification.forEach((item, index) => {
      const last = combination[index]
      item.value.forEach(element => {
        combination[index] = element.id
        element.enable = this.hasStock(combination)
      })
      combination[index] = last
    })
    this.setData({ specification: this.data.specification })
  },
  /**
   * 检查当前规格的库存
   * @param {array} sku 规格 id 组成的数组
   */
  hasStock(sku) {
    loop:
    for (let index in this.data.sku) {
      let specification = index.split('_').map(item => item * 1)
      for(let key in sku) {
        if (!specification.includes(sku[key])) {
          continue loop
        }
      }
      return this.data.sku[index].stock * 1 > 0
    }
    return false
  },
  decrease() {
    if (this.data.number <= 1) {
      wx.showToast({ title: '数量不能再减少了', icon: 'none', duration: 1500, mask: false })
      return
    }
    this.setData({ number: this.data.number - 1 })
  },
  increase() {
    if (this.data.number >= this.data.selectedSku.stock) {
      wx.showToast({ title: '数量不能再增加了', icon: 'none', duration: 1500, mask: false })
      return
    }
    this.setData({ number: this.data.number + 1 })
  },
  /**
   * 获取商品详情
   * @param {number} id 商品 id
   */
  async getGoodsDetail() {
    try {
      const res = await goodsDetail({
        data: { goods_id: this.pageData.goodsId },
        callback: wx.hideLoading
      })
      if (res.code === API_OK) {
        // console.log(res)
        const { data } = res
        const sku = data.detail.sku.reduce((obj,item) => {
          obj[item.spec_sku_id] = {
            id: item.goods_sku_id,
            price: item.goods_price,
            originPrice: item.line_price,
            stock: item.stock_num,
            specification: item.spec_sku_id,
            sales: item.goods_sales
          }
          return obj
        }, {})
        this.setData({
          goodsType: data.detail.goods_cate,
          goodsId: data.detail.goods_id,
          images: data.detail.image.map(item => item.file_path),
          detail: data.detail.content,
          likeNum: data.detail.like_count,
          credit: data.detail.score_deduct * 1,
          isFavourite: !!data.detail.myLike,
          name: data.detail.goods_name,
          video: data.detail.goods_video,
          sku,
          specification: data.spec && data.spec.spec_attr.map(item => {
            return {
              name: item.group_name,
              value: item.spec_items.map(item => {
                return { id: item.item_id, name: item.spec_value }
              })
            }
          }),
          selectedSku: sku[Object.keys(sku)[0]],
          selectedSpecification: data.spec && data.detail.sku[0].spec_sku_id.split('_').map(item => item * 1)
        })
        data.spec && this.checkSpecificationChosable()
      }
    } catch(err) {
      console.warn(err)
    }
  },
  /**
   * 获取评价列表
   */
  async getEvaluate() {
    try {
      this.data.loading = true
      const res = await evaluateList({
        data: {
          id: this.pageData.goodsId,
          type: 1,
          page: this.pageData.page
        }
      })
      this.data.loading = false
      // console.log(res)
      if (res.code === API_OK) {
        this.pageData.canLoadMore = res.data.current_page < res.data.last_page
        this.setData({
          evaluates: [...this.data.evaluates, ...(res.data.data.map(item => {
            return {
              star: item.score,
              userName: item.user.nickName,
              content: item.content
            }
          }))]
        })
      }
    } catch(err) {
      console.warn(err)
      this.data.loading = false
    }
  },
  onPageScroll({scrollTop}) {
    let btnType, bgColor

    if (scrollTop >= (app.globalData.viewportWidth - app.globalData.headerHeight)) {
      btnType = 'common'
      bgColor = '#fff'
    } else {
      btnType = 'circle'
      bgColor = 'transparent'
    }
    if (btnType !== this.data.headerBtnType) {
      if (btnType === 'circle') {
        wx.setNavigationBarColor({ frontColor: '#ffffff', backgroundColor: '#000000' })
      } else {
        wx.setNavigationBarColor({ frontColor: '#000000', backgroundColor: '#000000' })
      }
      this.setData({ headerBtnType: btnType, headerBgColor: bgColor })
    }
  },
  preventScroll(e) {},
  closeDialog() {
    this.setData({ showSpecifications: false })
  },
  /**
   * 商品加入收藏
   */
  async toggleFavourite() {
    try {
      wx.showLoading({ title: '正在加入收藏', mask: true })
      const res = this.data.isFavourite
      ? await cancelFavourite({
        data: { goods_id: this.data.goodsId, type: 1 },
        callback: wx.hideLoading
      })
      : await addFavourite({
        data: { goods_id: this.data.goodsId, type: 1 },
        callback: wx.hideLoading
      })
      // console.log(res)
      if (res.code === 200) {
        this.data.isFavourite
          ? wx.showToast({ title: '取消收藏成功', icon: 'success', duration: 1500, mask: true })
          : wx.showToast({ title: '加入收藏成功', icon: 'success', duration: 1500, mask: true })
        this.setData({
          isFavourite: !this.data.isFavourite,
          likeNum: this.data.isFavourite ? Math.max(this.data.likeNum - 1, 0) : this.data.likeNum + 1
        })
      }
    } catch(err) {
      console.warn(err)
    }
  },
  /**
   * 规格弹窗的确定操作
   */
  submit() {
    if (!this.data.selectedSku) {
      wx.showToast({ title: '请选择商品属性！', duration: 1500, mask: true, icon: 'none' })
      return
    }
    if (this.data.confirmType === 'cart') {
      this.addCart()
    } else {
      const type = this.data.goodsType === 2 ? 'credit' : 'buyNow'
      wx.navigateTo({
        url: `/pages/confirm-order/confirm-order?order_type=${type}&goods_id=${this.data.goodsId}&goods_num=${this.data.number}&goods_sku_id=${this.data.selectedSku.specification}&credit=${this.data.credit}`
      })
    }
  },
  /**
   * 添加商品到购物车
   */
  async addCart() {
    if (this.pageData.submit) return
    this.pageData.submit = true
    this.setData({ showSpecifications: false })
    wx.showLoading({ title: '正在加入购物车', mask: true })
    try {
      const res = await addCart({
        header: { 'Content-Type': 'application/x-www-form-urlencoded' },
        data: {
          goods_id: this.data.goodsId,
          goods_num: this.data.number,
          goods_sku_id: this.data.selectedSku.specification
        },
        callback: wx.hideLoading
      })
      console.log(res)
      this.pageData.submit = false
      if (res.code === API_OK) {
        wx.showToast({ title: '加入购物车成功！', icon: 'success', duration: 1500, mask: false })
      }
    } catch(err) {
      console.warn(err)
      this.pageData.submit = false
    }
  }
})
